package com.hafu.dao;

import com.hafu.model.LiveClass;
import com.hafu.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

// 直播课程数据访问对象
public class LiveClassDao {
    private static Connection conn;

    public LiveClassDao() {
        conn = DbUtil.getConn();
    }

    public List<LiveClass> getAllLiveClasses() {
        List<LiveClass> liveClasses = new ArrayList<>();
        String sql = "SELECT * FROM live_class ORDER BY live_time DESC";

        try (PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                liveClasses.add(new LiveClass(
                        rs.getString("class_id"),
                        rs.getString("class_name"),
                        rs.getString("teacher_id"),
                        rs.getString("live_time"),
                        rs.getString("status")
                ));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return liveClasses;
    }

    public List<LiveClass> searchLiveClasses(String keyword) {
        List<LiveClass> liveClasses = new ArrayList<>();
        String sql = "SELECT * FROM live_class WHERE class_name LIKE ? ORDER BY live_time DESC";

        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, "%" + keyword + "%");

            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    liveClasses.add(new LiveClass(
                            rs.getString("class_id"),
                            rs.getString("class_name"),
                            rs.getString("teacher_id"),
                            rs.getString("live_time"),
                            rs.getString("status")
                    ));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return liveClasses;
    }

    public boolean joinLiveClass(String classId) {
        if (classId == null || classId.trim().isEmpty()) {
            return false;
        }

        // 这里应该记录用户加入直播的日志
        // 简化示例，直接返回成功
        return true;
    }
}
